import React, { useState, useRef } from 'react';
import { Form, Input, Select, Upload, Button, Table, message, Space, Popconfirm, Tag, Tooltip, Modal } from 'antd';
import { InboxOutlined, EditOutlined, PaperClipOutlined, EyeOutlined } from '@ant-design/icons';
import './ApprovalEdit.jsx.css';

const { Dragger } = Upload;
const { TextArea } = Input;
const { Option } = Select;

const mockAttachments = [
    { id: 1, name: '200916142507.jpg', file_path: 'upload/2023/10/01/200916142507.jpg', uploader_id: 1, upload_time: '2023-10-01', status: 1 },
    { id: 2, name: '200916142508.jpg', file_path: 'upload/2023/10/02/200916142508.jpg', uploader_id: 1, upload_time: '2023-10-02', status: 1 },
];
const mockApprovalItem = [
    { id: 1, name: '上海中心大厦项目采购' },
    { id: 2, name: '花园项目采购' },
];

const initialApprovals = [
    {
        id: 'APP-2023-101',
        name: '项目采购申请',
        type: 1,
        approval_item: 1,
        remark: '包含各种材料',
        attachments: [1, 2],
        status: 2,
        create_time: '2023-10-01',
        end_time: '2023-10-05'
    },
];

const typeMap = {
    1: '采购审批',
    2: '财务审批',
    3: '人事审批',
    4: '项目审批',
    5: '行政审批'
};
const statusMap = {
    1: '草稿',
    2: '审批中',
    3: '退回',
    4: '已完成',
    5: '已取消',
    6: '已拒绝'
};

const ApprovalEditPage = () => {
    const [approvals, setApprovals] = useState(initialApprovals);
    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const fileInputRef = useRef(null);

    const handleEdit = (record) => {
        setCurrentRecord(record);
        form.setFieldsValue({
            ...record,
            attachments: {
                fileList: mockAttachments.filter(f => record.attachments.includes(f.id))
                    .map(f => ({ uid: f.id, name: f.name, status: 'done', url: f.file_path }))
            }
        });
        setIsModalVisible(true);
    };

    const handleSave = async () => {
        try {
            const values = await form.validateFields();

            const updated = {
                ...currentRecord,
                ...values,
                attachments: values.attachments?.fileList?.map(f => f.uid || f.id) || []
            };

            let newList;
            if (currentRecord) {
                newList = approvals.map((item) =>
                    item.id === currentRecord.id ? updated : item
                );
            } else {
                newList = [...approvals, { ...updated, id: `APP-${Date.now()}` }];
            }

            setApprovals(newList);
            setIsModalVisible(false);
            message.success('审批信息已保存');
        } catch (error) {
            console.error('表单验证失败:', error);
            message.error('请完善必填信息');
        }
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const handleSearch = (value) => setSearchTerm(value);
    const handleStatusFilter = (value) => setStatusFilter(value);
    const handleCreateApproval = () => {
        setCurrentRecord(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const getFilteredApprovals = () => {
        return approvals.filter((approval) => {
            const matchesSearch =
                approval.id.includes(searchTerm) || approval.name.includes(searchTerm);
            const matchesStatus = statusFilter === 'all' || approval.status === Number(statusFilter);
            return matchesSearch && matchesStatus;
        });
    };

    const uploadProps = {
        name: 'file',
        multiple: true,
        action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
        onChange(info) {
            const { status } = info.file;
            if (status === 'done') {
                message.success(`${info.file.name} 上传成功`);
            } else if (status === 'error') {
                message.error(`${info.file.name} 上传失败`);
            }
        },
        showUploadList: {
            showDownloadIcon: true,
            downloadIcon: <EyeOutlined onClick={(e) => {
                e.stopPropagation();
                message.info('预览功能待实现');
            }} />,
        },
    };

    const renderStatusTag = (status) => {
        let color;
        switch (status) {
            case 2: color = 'processing'; break; // 审批中
            case 4: color = 'success'; break; // 已完成
            case 6: color = 'error'; break; // 已拒绝
            default: color = 'default';
        }
        return <Tag color={color}>{statusMap[status]}</Tag>;
    };

    const columns = [
        { title: '审批ID', dataIndex: 'id', key: 'id', width: 150 },
        {
            title: '名称', dataIndex: 'name', key: 'name', width: 180,
            render: (text, record) => (
                <Tooltip title="点击编辑" placement="top">
                    <span className="approval-edit-editable-cell" onClick={() => handleEdit(record)}>
                        {text}
                    </span>
                </Tooltip>
            )
        },
        { title: '类型', dataIndex: 'type', key: 'type', width: 120, render: (t) => <Tag color="blue">{typeMap[t]}</Tag> },
        { title: '状态', dataIndex: 'status', key: 'status', width: 100, render: renderStatusTag },
        { title: '事项', dataIndex: 'approval_item', key: 'approval_item', width: 180, render: (id) => mockApprovalItem.find(i => i.id === id)?.name || '-' },
        { title: '备注', dataIndex: 'remark', key: 'remark', width: 200 },
        {
            title: '附件',
            dataIndex: 'attachments',
            key: 'attachments',
            width: 200,
            render: (ids) => ids && ids.length > 0 ? (
                <div>
                    {ids.map((id) => {
                        const file = mockAttachments.find(f => f.id === id);
                        return file ? (
                            <div key={id}>
                                <PaperClipOutlined style={{ marginRight: 5 }} />
                                <a href={file.file_path} target="_blank" rel="noreferrer">{file.name}</a>
                            </div>
                        ) : null;
                    })}
                </div>
            ) : <span>无附件</span>
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="primary"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                        size="small"
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此审批吗？"
                        onConfirm={() => {
                            setApprovals(approvals.filter(item => item.id !== record.id));
                            message.success('审批已删除');
                        }}
                    >
                        <Button danger size="small">删除</Button>
                    </Popconfirm>
                </Space>
            )
        }
    ];

    return (
        <div className="approval-edit-container">
            <div className="approval-edit-page-header">
                <h2>审批申请管理</h2>
                <p>编辑和审批您的申请记录</p>
            </div>
            <div className="approval-edit-toolbar">
                <Button type="primary" onClick={handleCreateApproval}>新建审批</Button>
                <div className="approval-edit-search-area">
                    <Input.Search
                        placeholder="搜索审批ID或名称"
                        allowClear
                        onSearch={handleSearch}
                        onChange={(e) => handleSearch(e.target.value)}
                        style={{ width: 250 }}
                    />
                    <Select defaultValue="all" style={{ width: 120, marginLeft: 10 }} onChange={handleStatusFilter}>
                        <Option value="all">全部状态</Option>
                        {Object.entries(statusMap).map(([k, v]) => (
                            <Option key={k} value={k}>{v}</Option>
                        ))}
                    </Select>
                </div>
            </div>

            <Table
                columns={columns}
                dataSource={getFilteredApprovals().map(item => ({ ...item, key: item.id }))}
                rowKey="id"
                pagination={{ pageSize: 5, showSizeChanger: true }}
                bordered
                size="middle"
                scroll={{ x: 1300 }}
            />

            <Modal
                title={currentRecord ? "编辑审批信息" : "新建审批信息"}
                open={isModalVisible}
                onOk={handleSave}
                onCancel={handleCancel}
                width={800}
                footer={[
                    <Button key="back" onClick={handleCancel}>取消</Button>,
                    <Button key="submit" type="primary" onClick={handleSave}>保存</Button>
                ]}
            >
                <Form form={form} layout="vertical" initialValues={currentRecord}>
                    <Form.Item name="name" label="审批名称" rules={[{ required: true }]}><Input /></Form.Item>
                    <Form.Item name="type" label="审批类型" rules={[{ required: true }]}>
                        <Select placeholder="请选择审批类型">
                            {Object.entries(typeMap).map(([k, v]) => (
                                <Option key={k} value={Number(k)}>{v}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="approval_item" label="审批事项" rules={[{ required: true }]}>
                        <Select placeholder="请选择审批事项">
                            {mockApprovalItem.map(i => (
                                <Option key={i.id} value={i.id}>{i.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="remark" label="备注信息"><TextArea rows={3} /></Form.Item>
                    <Form.Item name="attachments" label="相关附件">
                        <Dragger {...uploadProps}>
                            <p className="ant-upload-drag-icon"><InboxOutlined /></p>
                            <p className="ant-upload-text">点击或拖拽文件到此处</p>
                        </Dragger>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ApprovalEditPage;
